//
//  ShakeVC.m
//  DaleTou
//
//  Created by candyxj on 2018/5/27.
//  Copyright © 2018年 geren. All rights reserved.
//

#import "ShakeVC.h"
#import "Appearance.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
//#import <AudioToolbox/AudioToolbox.h>
#import <CoreAudio/CoreAudioTypes.h>
#import "PopNumberView.h"
#import "UIView+CustomAlertView.h"
#import "LotteryOrderView.h"
#import "ShareValue.h"
#import "OrderBillViewController.h"
#import "zhoushiViewController.h"
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface ShakeVC ()<UIResponderStandardEditActions>{
    
    PopNumberView *_popView;
}
@property (nonatomic, strong) NSMutableArray *readArray;
@property (nonatomic, strong) NSMutableArray *bluearray;

@property (nonatomic, strong) LotteryOrderView *lotteryOrderView;

@property (nonatomic, strong) AVAudioPlayer * audioPlayer;
@end

@implementation ShakeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    

    self.view.backgroundColor = [UIColor colorWithHexString:@"ffffff"];
    [self setNavConfigStartColor:@"#F57321" endColor:@"#F57321"];
    [self ApptitileView:@"摇一摇"];
    
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, Main_Screen_Width, Main_Screen_Height - NAVIGATION_BAR_HEIGHT)];
    bgImageView.image = [UIImage imageNamed:@"摇摇"];
    [self.view addSubview:bgImageView];
    
    
    // 设置允许摇一摇功能
    [UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
    // 并让自己成为第一响应者
    [self becomeFirstResponder];
}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    NSLog(@"开始摇动");
    
    [_popView jk_hideView];
    
    //播放音效
    SystemSoundID   soundID;  // shake_sound_male.mp3
    NSString *path = [[NSBundle mainBundle ] pathForResource:@"shake_sound_male" ofType:@"mp3"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
    AudioServicesPlaySystemSound (soundID);
    return;
}

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    NSLog(@"取消摇动");
    return;
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.subtype == UIEventSubtypeMotionShake) { // 判断是否是摇动结束
        NSLog(@"摇动结束");
        [self shakeshake];
        
        _popView = [[PopNumberView alloc] initWithFrame:CGRectMake(0, 0, 250, 250)];
        [_popView jk_showInWindowWithMode:JKCustomAnimationModeAlert inView:nil bgAlpha:0.2 needEffectView:YES];
        _popView.commitBtnClickedBlock = ^(NSArray *arr) {
            NSLog(@"数组%@",arr);
            if ([ShareValue sharedInstance].isLogin) {
                [self.view addSubview:self.lotteryOrderView];
                NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
                NSTimeInterval a = [dat timeIntervalSince1970];
                NSString *timeString = [NSString stringWithFormat:@"%.f", a];
                _lotteryOrderView.orderNumber = timeString;
                
                NSTimeInterval openTimeInter = [NSDate date].timeIntervalSince1970 + 60 * 10;
                NSDateFormatter *famtter = [[NSDateFormatter alloc] init];
                [famtter setDateFormat:@"yyyy-MM-dd HH:mm"];
                NSDate *date = [NSDate dateWithTimeIntervalSince1970:openTimeInter];
                NSString *dateString = [famtter stringFromDate:[NSDate date]];
                _lotteryOrderView.openTime = dateString;
                _lotteryOrderView.jiangchijine = @"68万";
                NSString *zhudanstr = @"1注 共2元";
                _lotteryOrderView.zhudan = zhudanstr;
                for (int i = 0; i < arr.count; i++) {
                    if (i <= 4) {
                        [self.readArray addObject:[NSString stringWithFormat:@"%@ ",arr[i]]];
                    }else{
                        [self.bluearray addObject:[NSString stringWithFormat:@"%@ ",arr[i]]];
                    }
                }
                NSString *redstr = [self.readArray componentsJoinedByString:@" "];
                
                NSString *bluestr = [self.bluearray componentsJoinedByString:@" "];
                
                NSString *touzhuStr = [NSString stringWithFormat:@"%@ %@",redstr,bluestr];
                NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:touzhuStr];
                
                [attrStr addAttribute:NSForegroundColorAttributeName
                                value:[UIColor redColor]
                                range:NSMakeRange(0, redstr.length)];
                [attrStr addAttribute:NSForegroundColorAttributeName
                                value:[UIColor blueColor]
                                range:NSMakeRange(redstr.length + 1, bluestr.length)];
                _lotteryOrderView.attributedMyNumber = attrStr;
                _lotteryOrderView.beishu = @"1倍";
                _lotteryOrderView.twoBtnLookDetailBtnClickedBlock = ^{
                    OrderBillViewController *vc = [[OrderBillViewController alloc] init];
                    vc.isOrderBill = YES;
                    [self.readArray removeAllObjects];
                    [self.bluearray removeAllObjects];
                    [self.navigationController pushViewController:vc animated:YES];
                };
                
                _lotteryOrderView.contrlInfoBtnClickedBlock = ^{
                    [self.readArray removeAllObjects];
                    [self.bluearray removeAllObjects];
                    zhoushiViewController *vc = [[zhoushiViewController alloc] init];
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                };
                
                _lotteryOrderView.twoBtnOneMoreBtnClickedBlock = ^{
                    [self.readArray removeAllObjects];
                    [self.bluearray removeAllObjects];
                };
                //存数据
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                //获取完整路径
                NSString *documentsDirectory = [paths objectAtIndex:0];
                
                NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"MyOrderList.plist"];//这里就是你将要存储的沙盒路径（.plist文件，名字自定义）
                NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
                if (!array) {
                    array = [NSMutableArray array];
                }
                NSDictionary *dic = @{@"redStr" : redstr,@"blueStr":bluestr, @"caizhong" : @"超级大乐透",@"zhudan":@"1注2元",@"dingdanhao":timeString,@"jiangchijine":@"68万",@"kaijiangshijian":dateString, @"beishu":@"1倍",@"touzhushijian":[NSDate date]};
                [array insertObject:dic atIndex:0];
                [array writeToFile:plistPath atomically:YES];
            }else{
                [self presentViewController:self.loginNav animated:YES completion:nil];
            }
        };
    }
    return;
}

//  摇动结束后执行震动
- (void)shakeshake {
    // 震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}


- (NSString *)getTomorrowDay:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    
    
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"yyyy-MM-dd"];
    return [dateday stringFromDate:beginningOfWeek];
}

- (LotteryOrderView *)lotteryOrderView{
    if (_lotteryOrderView == nil) {
        _lotteryOrderView = [LotteryOrderView initView];
        _lotteryOrderView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        _lotteryOrderView.layer.cornerRadius = 5;
        _lotteryOrderView.layer.masksToBounds = YES;
    }
    return _lotteryOrderView;
}

-(NSMutableArray *)readArray{
    if (!_readArray) {
        _readArray = [NSMutableArray array];
    }
    return _readArray;
}

-(NSMutableArray *)bluearray{
    if (!_bluearray) {
        _bluearray = [NSMutableArray array];
    }
    return _bluearray;
}

@end
